﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public enum MESSAGEPOPUPTYPE
{
	IMPOSSIBLENICKNAME,
	DUPULICATENICKNAME,
	CLIENTVERSIONMATCH,
	SERVERERROR,
	DISCONNECT,
	BUYITEM,
	NotEnoughGold,
	NotEnoughCash,
	DeleteFriend,
	FacebookConnect,
	CancelDeckEditWarning,
	UCUpdaterFailed,
	SellUnitWarning,
	LevelUP,
	InvenCountLimit,
	ClientCrashorException,
    WebServerException,
    ReceiveGameInviteFromFriend,
    NoMoreExistGame,
    NotEnoughStaminaForStartGame,
    SeveralErrorForStartGame,
	SuccessBuyShopItem,
	TableDataError,
	NoSettingTeam
};

public class MessagePopup : MonoBehaviour {
	public delegate void MessagePopupCallback(MESSAGEPOPUPTYPE type, bool isYes);
    public static MessagePopup window
    {
        get
        {
            if (_window == null)
            {
                // Instantiate loading window.
                // Awake() will set its position.
                _window = LTPrefabManager.InstantiateC(PrefabTypes.Panel_MessagePopup).GetComponent<MessagePopup>();
                UIRoot root = GameObject.Find("UI Root (2D)").GetComponent<UIRoot>();
                if (root != null)
                {
					Camera cam = null;
                    //if( root.transform.FindChild("PopupCamera") != null )
                    //    cam = root.transform.FindChild("PopupCamera").GetComponent<Camera>();

                    //if (cam != null)
                    //{
                    //    UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
                    //    if (anchor != null)
                    //    {
                    //        _window.transform.parent = anchor.transform;
                    //        _window.transform.localPosition = new Vector3(_window.transform.localPosition.x, _window.transform.localPosition.y, -10f);
                    //        _window.transform.localScale = Vector3.one;
                    //        _window.GetComponent<UIPanel>().depth = 40;

                    //        Camera mainCam = root.transform.FindChild("Camera").GetComponent<Camera>();
                    //        if( mainCam.GetComponent<Blur>() == null )
                    //            mainCam.gameObject.AddComponent<Blur>();
                    //        mainCam.GetComponent<Blur>().enabled = true;
                    //    }
                    //}
                    //else
					{
						Debug.LogError("Camera");
						cam = root.transform.FindChild("Camera").GetComponent<Camera>();
						if (cam != null)
						{
							UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
							if (anchor != null)
							{
								_window.transform.parent = anchor.transform;
								_window.transform.localPosition = new Vector3(_window.transform.localPosition.x, _window.transform.localPosition.y, -10f);
								_window.transform.localScale = Vector3.one;
								_window.GetComponent<UIPanel>().depth = 40;
							}
						}
					}
                }
            }
            return _window;
        }
    }
	
	private static MessagePopup _window;
	public GameObject closeButton;
	public GameObject okButton;
	public GameObject cancelButton;
	
	public UILabel titleLabel;
	public UILabel bodyLabel;
	
	Transform myTransform;
	
	MESSAGEPOPUPTYPE _type;

	public GameObject warningMark;

	public GameObject blckBG;
	
	void Awake()
    {
        _window = this;
        DontDestroyOnLoad(_window.gameObject);
        //_collider = this.gameObject.collider as BoxCollider;
//        _collider = this.gameObject.GetComponentInChildren<BoxCollider>();
        myTransform = transform;
        Application.backgroundLoadingPriority = ThreadPriority.High;
//        HideLoading();
    }

    public bool isShowingPopup(MESSAGEPOPUPTYPE type)
    {
        if( _type == type && gameObject.activeSelf )
            return true;
        
        return false;
    }

	public void ShowPopup(MESSAGEPOPUPTYPE type)
	{
        Debug.LogError("ShowPopup - " + type);
		ShowPopup(type, null, null);
	}
	
	MessagePopupCallback _callback;
	public void ShowPopup(MESSAGEPOPUPTYPE type, string[] param, MessagePopupCallback callback)
	{
        Debug.LogError("ShowPopup - " + type);
		if(CSceneManager.isReplay)
		{
			if(_window!=null)
				_window.gameObject.SetActive(false);
			return;
		}
		_type = type;
		_callback = callback;
		switch(type)
		{
		case MESSAGEPOPUPTYPE.IMPOSSIBLENICKNAME:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			warningMark.SetActive(true);
//			closeButton.SetActive(false);
//			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1621).Replace("\\n", "\n"));
			break;
		case MESSAGEPOPUPTYPE.DUPULICATENICKNAME:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			warningMark.SetActive(true);
//			closeButton.SetActive(false);
//			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1621).Replace("\\n", "\n"));
			break;
		case MESSAGEPOPUPTYPE.CLIENTVERSIONMATCH:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
//			closeButton.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1621).Replace("\\n", "\n"));
			break;
		case MESSAGEPOPUPTYPE.SERVERERROR:
		case MESSAGEPOPUPTYPE.DISCONNECT:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1620).Replace("\\n", "\n"));
			break;
		case MESSAGEPOPUPTYPE.BUYITEM:
			okButton.SetActive(true);
			cancelButton.SetActive(true);
			//closeButton.SetActive(false);
			string temp = CStringTableManager.Instance.GetItemById(1615);
			temp = temp.Replace("{ItemName}", param[0]);
			ShowPopup("NOTICE", temp);
			break;
		case MESSAGEPOPUPTYPE.NotEnoughGold:
			okButton.SetActive(true);
			cancelButton.SetActive(true);
			//closeButton.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1619));
			break;
		case MESSAGEPOPUPTYPE.NotEnoughCash:
			okButton.SetActive(true);
			cancelButton.SetActive(true);
			//closeButton.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1618));
			break;
		case MESSAGEPOPUPTYPE.DeleteFriend:
			okButton.SetActive(true);
			cancelButton.SetActive(true);
			//closeButton.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1617));
			break;
		case MESSAGEPOPUPTYPE.FacebookConnect:
			okButton.SetActive(true);
			cancelButton.SetActive(true);
			//closeButton.gameObject.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1616));
			break;
		case MESSAGEPOPUPTYPE.CancelDeckEditWarning:
			okButton.SetActive(true);
			cancelButton.SetActive(true);
			//closeButton.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1660));
			break;
		case MESSAGEPOPUPTYPE.UCUpdaterFailed:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			ShowPopup("NOTICE", param[0]);
			break;
		case MESSAGEPOPUPTYPE.SellUnitWarning:  
			okButton.SetActive(true);
			cancelButton.SetActive(true);
			//closeButton.SetActive(false);
			string body = CStringTableManager.Instance.GetItemById(1855).Replace("\\n", "\n");
			body += "\n\n"+CStringTableManager.Instance.GetItemById(1112)+" "+param[0];
			ShowPopup("NOTICE", body);
			break;
		case MESSAGEPOPUPTYPE.LevelUP:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			//closeButton.SetActive(true);
			ShowPopup(CStringTableManager.Instance.GetItemById(1876), CStringTableManager.Instance.GetItemById(1877).Replace("{prev}", "LV."+MyInfo.Instance.userLevel).Replace("{current}", "LV."+MyInfo.Instance.nextUserLevel));
                
			break;
		case MESSAGEPOPUPTYPE.InvenCountLimit:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			//closeButton.SetActive(true);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1882).Replace("\\n", "\n"));
			break;
		case MESSAGEPOPUPTYPE.ClientCrashorException:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			//closeButton.SetActive(true);
			ShowPopup("Client CRASH!!", param[0]+"\n\n"+param[1]);
			break;
        case MESSAGEPOPUPTYPE.WebServerException:
            okButton.SetActive(true);
            cancelButton.SetActive(false);
            //closeButton.SetActive(true);
            ShowPopup("WebServer Exception!!", param[0] + "\n\nStatusCode : " + param[1]);
            break;
        case MESSAGEPOPUPTYPE.ReceiveGameInviteFromFriend:
            Debug.LogError("ReceiveGameInviteFromFriend");
            okButton.SetActive(true);
            cancelButton.SetActive(true);
            //closeButton.SetActive(false);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1902).Replace("{friendName}", param[0]).Replace("\\n", "\n"));
            break;
        case MESSAGEPOPUPTYPE.NoMoreExistGame:
            okButton.SetActive(true);
            cancelButton.SetActive(false);
            //closeButton.SetActive(true);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1903).Replace("\\n", "\n"));
            break;
        case MESSAGEPOPUPTYPE.NotEnoughStaminaForStartGame:
            okButton.SetActive(true);
            cancelButton.SetActive(false);
            //closeButton.SetActive(true);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1904).Replace("\\n", "\n"));
            break;
        case MESSAGEPOPUPTYPE.SeveralErrorForStartGame:
            okButton.SetActive(true);
            cancelButton.SetActive(false);
            //closeButton.SetActive(true);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1901).Replace("\\n", "\n"));
            break;
		case MESSAGEPOPUPTYPE.SuccessBuyShopItem:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			//closeButton.SetActive(true);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(1905).Replace("{ItemName}", param[0]).Replace("\\n", "\n"));
			break;
		case MESSAGEPOPUPTYPE.TableDataError:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			//closeButton.SetActive(true);
			ShowPopup("NOTICE", param[1] + " is not exist in " + param[0] + "!!!!\nPlease Check Table!!!");
			break;
		case MESSAGEPOPUPTYPE.NoSettingTeam:
			okButton.SetActive(true);
			cancelButton.SetActive(false);
			//closeButton.SetActive(true);
			ShowPopup("NOTICE", CStringTableManager.Instance.GetItemById(2454).Replace("\\n", "\n"));
			break;
		}
	}
	
	public void ShowPopup(string title, string body)
	{
		LoadingWindow.window.HideLoading();
		if( _type == MESSAGEPOPUPTYPE.ClientCrashorException )
			bodyLabel.fontSize = 15;
		else
			bodyLabel.fontSize = 35;
//		gameObject.SetActive(false);
		titleLabel.text = title;
		bodyLabel.text = body;

		if( okButton.activeSelf && !cancelButton.activeSelf )
		{
			Vector3 pos = okButton.transform.localPosition;
			pos.x = 0;
			okButton.transform.localPosition = pos;
		}
		else if( okButton.activeSelf && cancelButton.activeSelf )
		{
			Vector3 pos = okButton.transform.localPosition;
			pos.x = 150f;
			okButton.transform.localPosition = pos;
			pos = cancelButton.transform.localPosition;
			pos.x = -150f;
			cancelButton.transform.localPosition = pos;
		}

		if( warningMark.activeSelf )
		{
			Vector3 pos = bodyLabel.transform.localPosition;
			pos.y = -30f;
			bodyLabel.transform.localPosition = pos;
		}
		else
		{
			Vector3 pos = bodyLabel.transform.localPosition;
			pos.y = 0f;
			bodyLabel.transform.localPosition = pos;
		}

        //if( CSceneManager.m_Scene == SCENE.GoToStageScene )
        //    blckBG.SetActive(true);
        //else
        //    blckBG.SetActive(false);
		
		UIRoot root = GameObject.Find("UI Root (2D)").GetComponent<UIRoot>();
        if (root != null)
        {
			Camera cam = null;
            //if( root.transform.FindChild("PopupCamera") != null )
            //    cam = root.transform.FindChild("PopupCamera").GetComponent<Camera>();

            //if (cam != null)
            //{
            //    UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
            //    if (anchor != null)
            //    {
            //        myTransform.gameObject.layer = anchor.gameObject.layer;
            //        SetAllChildTransformLayer(myTransform, myTransform.gameObject.layer);

            //        _window.transform.parent = anchor.transform;
            //        _window.transform.localPosition = new Vector3(_window.transform.localPosition.x, _window.transform.localPosition.y, -10f);
            //        _window.transform.localScale = Vector3.one;
            //        _window.GetComponent<UIPanel>().depth = 40;
					
            //        Camera mainCam = root.transform.FindChild("Camera").GetComponent<Camera>();
            //        if( mainCam.GetComponent<Blur>() == null )
            //            mainCam.gameObject.AddComponent<Blur>();
            //        mainCam.GetComponent<Blur>().enabled = true;
            //    }
            //}
            //else
			{
				Debug.LogError("Camera");
				cam = root.transform.FindChild("Camera").GetComponent<Camera>();
				if (cam != null)
				{
					UIAnchor anchor = cam.gameObject.GetComponentInChildren<UIAnchor>();
					if (anchor != null)
					{
						myTransform.gameObject.layer = anchor.gameObject.layer;
                        if( CSceneManager.m_Scene == SCENE.MainScene )
                            SetAllChildTransformLayer(myTransform, LayerMask.NameToLayer("GUI_TOP"));
                        else
						    SetAllChildTransformLayer(myTransform, myTransform.gameObject.layer);

						_window.transform.parent = anchor.transform;
						_window.transform.localPosition = new Vector3(_window.transform.localPosition.x, _window.transform.localPosition.y, -10f);
						_window.transform.localScale = Vector3.one;
						_window.GetComponent<UIPanel>().depth = 40;
					}
				}
			}
		}
		myTransform.localPosition = Vector3.zero;
		myTransform.localScale = Vector3.one;
//		if( CSceneManager.m_Scene == SCENE.InGameScene )
//		{
//			foreach(Transform obj in myTransform)
//			{
//				obj.gameObject.layer = myTransform.parent.gameObject.layer;
//			}
//		}
//		else
//		{
//			foreach(Transform obj in myTransform)
//			{
//				obj.gameObject.layer = myTransform.parent.gameObject.layer;
//			}
//		}
	}
	
	public void HidePopup()
	{
		Debug.LogError("HideLoading");
        myTransform.transform.parent = null;
		myTransform.localPosition = new Vector3(1000f, 1000f, 0f);

		UIRoot root = GameObject.Find("UI Root (2D)").GetComponent<UIRoot>();
		if (root != null)
		{
			Camera cam = root.transform.FindChild("Camera").GetComponent<Camera>();
			if (cam != null)
			{
				if( cam.GetComponent<Blur>() != null)
					cam.GetComponent<Blur>().enabled = false;
			}
		}
	}
	
	void OnClickOKButton()
	{
		Debug.LogError("닉네임"); 
		if( _callback != null )
			_callback(_type, true);
		HidePopup();
	}
	
	void OnClickCloseButton()
	{
        Debug.LogError("OnClickCloseButton");
		if( _callback != null && (_type == MESSAGEPOPUPTYPE.SERVERERROR || _type == MESSAGEPOPUPTYPE.DISCONNECT || _type == MESSAGEPOPUPTYPE.UCUpdaterFailed || _type == MESSAGEPOPUPTYPE.LevelUP ) )
			_callback(_type, false);
		HidePopup();
	}
		
	void GetAllChildTransform(Transform t, ref List<Transform> list)
	{
		foreach(Transform child in t)
		{
			list.Add(child);
			GetAllChildTransform(child, ref list);
		}
	}
	
	void SetAllChildTransformLayer(Transform t, int layerIndex)
	{
        t.gameObject.layer = layerIndex;
		foreach(Transform child in t)
		{
			child.gameObject.layer = layerIndex;
			SetAllChildTransformLayer(child, layerIndex);
		}
	}
}
